//index.js
//获取应用实例
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    banners: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    dataCount:0,
    tabs: ['', '', '', '', '', '', ''],
    stv: {
      windowWidth: 0,
      lineWidth: 0,
      offset: 0,
      tStart: false
    },
    activeTab: 0,
    hidden:false,
    cartHidden:true,
    goods: [],
    toView: '0',
    carArray: [],
    carHalfArray:[],
    url: "",
    showPopup: false,
    sfixed:false,
    food:{},
    rate:0,
  },
  onShow() {
    let cartGoods = app.globalData.cartGoods;
    let cartHalfGoods = app.globalData.cartHalfGoods;
    let dataCount = 0;
    cartGoods.filter(item => {
      dataCount += item.num;
    });
    cartHalfGoods.filter(item => {
      dataCount += item.num;
    });
    this.setData({
      carArray: cartGoods,
      carHalfArray: cartHalfGoods,
      dataCount: dataCount,
      goods: app.globalData.stoves
    });

    let that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          height: res.windowHeight
        })
      }
    })

  },
  onLoad: function(options) {
    try {
      //加载数据发起请求
      this.initData();
      
      let { tabs } = this.data;
      var res = wx.getSystemInfoSync()
      this.windowWidth = res.windowWidth;
      this.data.stv.lineWidth = this.windowWidth / this.data.tabs.length;
      this.data.stv.windowWidth = res.windowWidth;
      this.setData({
        stv: this.data.stv
      })
      this.tabsCount = tabs.length;
    } catch (e) {

    }
  },
  onPageScroll(e) {
    if (e.scrollTop >150){
      this.setData({
        sfixed:true
      })
    }else{
      this.setData({
        sfixed: false
      })
    }
  },
  handlerStart(e) {
    let {
      clientX,
      clientY
    } = e.touches[0];
    this.startX = clientX;
    this.tapStartX = clientX;
    this.tapStartY = clientY;
    this.data.stv.tStart = true;
    this.tapStartTime = e.timeStamp;
    this.setData({
      stv: this.data.stv
    })
  },
  handlerMove(e) {
    let {
      clientX,
      clientY
    } = e.touches[0];
    let {
      stv
    } = this.data;
    let offsetX = this.startX - clientX;
    this.startX = clientX;
    stv.offset += offsetX;
    if (stv.offset <= 0) {
      stv.offset = 0;
    } else if (stv.offset >= stv.windowWidth * (this.tabsCount - 1)) {
      stv.offset = stv.windowWidth * (this.tabsCount - 1);
    }
    this.setData({
      stv: stv
    });
  },
  handlerCancel(e) {

  },
  handleTap(e) {

  },
  handlerEnd(e) {
    let { clientX, clientY } = e.changedTouches[0];
    let endTime = e.timeStamp;
    let { tabs, stv, activeTab } = this.data;
    let { offset, windowWidth } = stv;
    //快速滑动
    if (endTime - this.tapStartTime <= 200) {
      //向左
      if (Math.abs(this.tapStartY - clientY) < 50) {
        if (this.tapStartX - clientX > 5) {
          if (activeTab < this.tabsCount - 1) {
            this.setData({
              activeTab: ++activeTab
            })
          }
        } else {
          if (activeTab > 0) {
            this.setData({
              activeTab: --activeTab
            })
          }
        }
        stv.offset = stv.windowWidth * activeTab;
      } else {
        //快速滑动 但是Y距离大于50 所以用户是左右滚动
        let page = Math.round(offset / windowWidth);
        if (activeTab != page) {
          this.setData({
            activeTab: page
          })
        }
        stv.offset = stv.windowWidth * page;
      }
    } else {
      let page = Math.round(offset / windowWidth);
      if (activeTab != page) {
        this.setData({
          activeTab: page
        })
      }
      stv.offset = stv.windowWidth * page;
    }
    stv.tStart = false;
    this.setData({
      stv: this.data.stv
    })
  },
  _updateSelectedPage(page) {
    let { tabs, stv, activeTab } = this.data;
    activeTab = page;
    this.setData({
      activeTab: activeTab
    })
    stv.offset = stv.windowWidth * activeTab;
    this.setData({
      stv: this.data.stv
    })
  },
  handlerTabTap(e) {
    this._updateSelectedPage(e.currentTarget.dataset.index);
  },
  /**
   * 跳转指定的餐别
   */
  selectMenu: function(e) {
    var index = e.currentTarget.dataset.itemIndex;
    this.setData({
      toView: 'order' + index.toString()
    })
  },
  /**
   * 根据类别查询数据
   */
  selectTypeList:function(e){
    wx.showLoading({
      title: '正在加载...',
    })
    var stoveIndex = e.currentTarget.dataset.stoveIndex;
    var mealsIndex = e.currentTarget.dataset.mealsIndex;
    var typeCode = e.currentTarget.dataset.typeCode;
    var list = app.globalData.stoves;
    for (var i = 0; i < list[stoveIndex].meals[mealsIndex].recipes.length;i++){
      if (list[stoveIndex].meals[mealsIndex].recipes[i].type_code==typeCode){
        list[stoveIndex].meals[mealsIndex].recipes[i].show=true;
      }else{
        list[stoveIndex].meals[mealsIndex].recipes[i].show = false;
      }
    }

    this.setData({
      goods: list,
      toView: 'order' + mealsIndex.toString()
    })
    app.globalData.stoves = list;
    wx.hideLoading();

  },
  //小份移除商品
  decreaseSmalCart: function (e) {
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;
    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum--;
    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount--;

    var id = this.data.food.id;
  
    var carList = this.data.carHalfArray;
    for (var m = 0; m < carList.length; m++) {
      if (carList[m].id == id) {
        carList.splice(m, 1); // a需要删除的位置,b删除几个
        break;
      }
    }

    this.data.food.xfCount--;
    this.setData({
      dataCount: this.data.dataCount - 1,
      carHalfArray: carList,
      goods: this.data.goods,
      food: this.data.food,
    })

    app.globalData.cartHalfGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  //大份移除商品
  decreaseBigCart:function(e){
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;

    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum--;
    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].count--;

    this.data.food.count--;
    var id = this.data.food.id;
    var num = this.data.food.count;
    var price = this.data.food.price;
    var cook_img = this.data.food.cook_img;
    var name = this.data.food.name;
    var meals = this.data.food.meals;
    var half_state = this.data.food.half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state: half_state
    };
    var carList = this.data.carArray.filter(item => item.id != id);
    carList.push(obj);
    for (var m = 0; m < carList.length; m++) {
      if (carList[m].num == 0) {
        carList.splice(m, 1); // a需要删除的位置,b删除几个
      }
    }
    this.setData({
      dataCount: this.data.dataCount - 1,
      carArray: carList,
      goods: this.data.goods,
      food: this.data.food
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  //移除商品
  decreaseCart: function(e) {
    var tabIndex = e.currentTarget.dataset.tabindex;
    var mealIndex = e.currentTarget.dataset.parentindex;
    var foodIndex = e.currentTarget.dataset.foodindex;

    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count--;

    var id = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].id;
    var num = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count;
    var price = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].price;
    var cook_img = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].cook_img;
    var name = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].name;
    var meals = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].meals;
    var half_state = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state: half_state
    };

    var carList = this.data.carArray.filter(item => item.id != id);
    carList.push(obj);
    for (var m = 0; m < carList.length; m++) {
      if (carList[m].num == 0) {
        carList.splice(m, 1); // a需要删除的位置,b删除几个
      }
    }
    this.setData({
      dataCount:this.data.dataCount - 1,
      carArray: carList,
      goods: this.data.goods
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  showAddCart(e){
    var food = e.currentTarget.dataset.food;
    var tabIndex = e.currentTarget.dataset.tabindex;
    var mealIndex = e.currentTarget.dataset.parentindex;
    var foodIndex = e.currentTarget.dataset.foodindex;
    food.tabIndex = tabIndex;
    food.mealIndex = mealIndex;
    food.foodIndex = foodIndex;

    let xfPrice = (food.price * this.data.rate).toFixed(2)
    if (!food["count"]) {
      food.count=0;
    }
    if (!food["xfCount"]) {
      food.xfCount = 0;
    }
    food.xfPrice = xfPrice;
    this.setData({
      cartHidden:false,
      food:food
    })
  },
  //小份添加到购物车
  addSmalCart(e) {
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;
    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["countSum"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum = 1;
    }
    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["xfCount"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount = 1;
    }
    

    var id = this.data.food.id;
    var num = 1;
    var price = this.data.food.price;
    var cook_img = this.data.food.cook_img;
    var name = this.data.food.name;
    var meals = this.data.food.meals;
    var half_state = this.data.food.half_state;
    var obj = {
      id: id,
      num: num,
      name: name+"--小份",
      price: (price*this.data.rate).toFixed(2),
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'y',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state
    };
    var carList = this.data.carHalfArray;
    carList.push(obj);

    this.data.food.xfCount++;
    this.setData({
      dataCount: this.data.dataCount + 1,
      carHalfArray: carList,
      goods: this.data.goods,
      food: this.data.food,
    })

    app.globalData.cartHalfGoods = carList;
    app.globalData.stoves=this.data.goods;
  },
  //大份添加到购物车
  addBigCart(e) {
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;

    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["countSum"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum = 1;
    }

    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["count"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].count++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].count = 1;
    }
    this.data.food.count++;

    var id = this.data.food.id;
    var num = this.data.food.count;
    var price = this.data.food.price;
    var cook_img = this.data.food.cook_img;
    var name = this.data.food.name;
    var meals = this.data.food.meals;
    var half_state = this.data.food.half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state: half_state
    };
    var carList = this.data.carArray.filter(item => item.id != id)
    carList.push(obj)

    this.setData({
      dataCount: this.data.dataCount + 1,
      carArray: carList,
      goods: this.data.goods,
      food: this.data.food
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  //添加到购物车
  addCart(e) {
    var tabIndex = e.currentTarget.dataset.tabindex;
    var mealIndex = e.currentTarget.dataset.parentindex;
    var foodIndex = e.currentTarget.dataset.foodindex;

    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["Count"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count = 1;
    }

    var id = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].id;
    var num = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count;
    var price = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].price;
    var cook_img = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].cook_img;
    var name = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].name;
    var meals = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].meals;
    var half_state = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state
    };
    var carList = this.data.carArray.filter(item => item.id != id)
    carList.push(obj)
    this.setData({
      dataCount: this.data.dataCount+1,
      carArray: carList,
      goods: this.data.goods
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  /**   
   * 预览图片  
   */
  togglePopup: function(event) {
    var image_path = event.currentTarget.dataset.id;
    this.setData({
      url: image_path,
      showPopup: !this.data.showPopup
    });
  },
  /**
   * 获取组分类
   */
  toTypeList(goods){
    for(let i=0;i<goods.length;i++){
      let meals = goods[i].meals;
      for (let j = 0; j < meals.length; j++) {
        let recipes = meals[j].recipes;
        let typeList=[];
        for (let k = 0; k < recipes.length; k++) {
          recipes[k].show=true;
          let typeItem = {"code": recipes[k].type_code, "name": recipes[k].type_name};
          if(typeList.length == 0){
            typeList.push(typeItem);
          }else{
            let flag = false;
            for (let y = 0; y < typeList.length; y++){
              if (typeList[y].code==typeItem.code){
                flag=true;
                break;
              }
            }
            if(!flag){
              typeList.push(typeItem);
            }
          }
        }
        meals[j].typeList = typeList;
      }
    }
    return goods;
  },
  initData(){
    let user = wx.getStorageSync("user");
    if (!user.bh) {
      wx.redirectTo({
        url: '../login/login',
      })
    }

    let _this = this;
    let param = {'patientId': user.bh };
    api.POST({
      url: 'homeH5.action',
      params: param,
      success: function (res) {
        let banner = res.data.data.banner;
        let rate = res.data.data.rate;
        let stoves = _this.toTypeList(res.data.data.stoves);
        _this.setData({
          banners: banner,
          goods: stoves,
          rate: rate
        })
        app.globalData.stoves = stoves;
      },
      fail: function () {
        wx.showToast({
          icon: 'none',
          title: '请求失败',
        })
      },
    })
  },
  cancel: function () {
    this.setData({
      hidden: true,
      cartHidden:true
    });
  },
})